<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- 数据类型 -->
      <el-form-item label="数据类型" prop="type">
        <el-select v-model.number="queryParams.type" placeholder="请选择数据类型" @change="handleQuery">
          <el-option label="升温" :value="1" />
          <el-option label="降温" :value="2" />
        </el-select>
      </el-form-item>


      <!-- 导入时间 -->
      <el-form-item label="导入时间" prop="importDay">
        <el-date-picker
          clearable
          v-model="queryParams.importDay"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择导入时间"
        />
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleDownloadTemplate">下载模板</el-button>
        <el-button type="success" icon="el-icon-upload" size="mini" @click="handleOpenImport">导入</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="historyList">
      <el-table-column label="数据类型" align="center" prop="type">
        <template slot-scope="scope">
          <span>{{ scope.row.type === 1 ? '升温' : '降温' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="钢坯前上表面" align="center" prop="data1" />
      <el-table-column label="中上表面" align="center" prop="data2" />
      <el-table-column label="后上表面" align="center" prop="data3" />
      <el-table-column label="钢坯前下表面" align="center" prop="data4" />
      <el-table-column label="中下表面" align="center" prop="data5" />
      <el-table-column label="后下表面" align="center" prop="data6" />
      <el-table-column label="钢坯前芯部" align="center" prop="data7" />
      <el-table-column label="中芯部" align="center" prop="data8" />
      <el-table-column label="后芯部" align="center" prop="data9" />
      <el-table-column label="导入时间" align="center" prop="importDay" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.importDay, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="180" />
      <el-table-column label="结束时间" align="center" prop="endTime" width="180" />
      <el-table-column label="备注" align="center" prop="remark" />
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 导入弹窗 -->
    <el-dialog title="导入钢坯温度历史记录" :visible.sync="importOpen" width="500px">
      <el-form ref="importForm" :model="importForm" label-width="120px">
        <el-form-item label="项目日期" prop="experimentDate">
          <el-select v-model="importForm.experimentDate" placeholder="请选择项目日期" @change="handleExperimentDateChange">
            <el-option v-for="item in experimentDates" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>

        <el-form-item label="时间范围" prop="timeRange">
          <el-select v-model="importForm.timeRange" placeholder="请选择时间范围">
            <el-option v-for="item in experimentTimeRanges" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="选择文件" prop="file">
          <el-upload
            ref="upload"
            :auto-upload="false"
            :file-list="fileList"
            :on-change="handleFileChange"
            :limit="1"
          >
            <el-button type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitImport">确 定</el-button>
        <el-button @click="importOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listHistory } from "@/api/businessInfo/history";
import request from "@/utils/request";

export default {
  data() {
    return {
      loading: false,
      total: 0,
      historyList: [],
      showSearch: true,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: 1,
        importDay: null
      },
      // 导入
      importOpen: false,
      importForm: { experimentDate: null, timeRange: null, file: null, type: 1 },
      fileList: [],
      experimentDates: [],
      experimentTimeRanges: []
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      listHistory(this.queryParams).then(res => {
        this.historyList = res.rows;
        this.total = res.total;
        this.loading = false;
      });
    },

    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.handleQuery();
    },

    /** 下载模板 */
    handleDownloadTemplate() {
      request({
        url: `/business/temphistory/downloadTemplate`,
        method: 'get',
        responseType: 'blob'
      }).then(res => {
        const blob = new Blob([res]);
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.setAttribute('download', `钢坯温度历史记录导入模版_${Date.now()}.xlsx`);
        document.body.appendChild(link);
        link.click();
        link.remove();
        window.URL.revokeObjectURL(link.href);
      });
    },

    /** 打开导入弹窗 */
    handleOpenImport() {
      this.importOpen = true;
      this.importForm = { experimentDate: null, timeRange: null, file: null, type: this.queryParams.type };
      this.fileList = [];
      request({ url: "/business/project/experimentTimes", method: "get" }).then(res => {
        if(res.code === 200) this.experimentDates = res.data;
      });
    },

    /** 项目日期变化 */
    handleExperimentDateChange(val) {
      this.importForm.timeRange = null;
      this.experimentTimeRanges = [];
      request({
        url: "/business/project/experimentTimeRangesByDate",
        method: "get",
        params: { experimentDate: val }
      }).then(res => {
        if(res.code === 200){
          this.experimentTimeRanges = res.data.map(item => ({
            label: `${item.startTime}-${item.endTime}`,
            value: `${item.startTime}-${item.endTime}`
          }));
        }
      });
    },

    handleFileChange(file) {
      this.importForm.file = file.raw;
      this.fileList = [file];
    },

    submitImport() {
      if(!this.importForm.experimentDate || !this.importForm.timeRange || !this.importForm.file){
        this.$message.warning("请完整填写导入信息");
        return;
      }
      const [startTime, endTime] = this.importForm.timeRange.split("-");
      const formData = new FormData();
      formData.append("type", this.importForm.type);
      formData.append("importDay", this.importForm.experimentDate);
      formData.append("startTime", startTime);
      formData.append("endTime", endTime);
      formData.append("file", this.importForm.file);

      request({
        url: "/business/temphistory/importData",
        method: "post",
        data: formData,
        headers: { "Content-Type": "multipart/form-data" }
      }).then(res => {
        if(res.code === 200){
          this.$message.success("导入成功");
          this.importOpen = false;
          this.getList();
        }else{
          this.$message.error(res.msg || "导入失败");
        }
      });
    },

    parseTime(time, format) {
      if(!time) return '';
      const date = new Date(time);
      const o = { y: date.getFullYear(), m: String(date.getMonth()+1).padStart(2,'0'), d: String(date.getDate()).padStart(2,'0') };
      return format.replace('{y}', o.y).replace('{m}', o.m).replace('{d}', o.d);
    }
  }
};
</script>
